package com.kgc.xsProvider.service.ServiceImpl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kgc.basic.util.PageInfo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.store.pojo.InStore;
import com.kgc.store.pojo.OutStore;
import com.kgc.xs.pojo.SalesInvoice;
import com.kgc.xs.pojo.SalesInvoiceDetail;
import com.kgc.xs.pojo.SalesOut;
import com.kgc.xs.pojo.SalesOutDetail;
import com.kgc.xsProvider.dao.SalesInvoiceMapper;
import com.kgc.xsProvider.service.SalesInvoiceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SalesInvoiceServiceImpl implements SalesInvoiceService {
    private Logger logger = LoggerFactory.getLogger(SalesInvoiceServiceImpl.class);

    @Autowired
    private SalesInvoiceMapper salesInvoiceMapper;

    @Override
    public ResponseMsg insertMainSalesInvoice(SalesInvoice salesInvoice) {
        ResponseMsg msg = new ResponseMsg();
        int i = salesInvoiceMapper.insertSalesInvoice(salesInvoice);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("增加销售发票主表数据成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("增加销售发票主表数据失败");
        return msg;
    }

    @Override
    public ResponseMsg selectSalesInvoiceByPage(Map<String, Object> map) {
        logger.info("SalesInvoiceServiceImpl selectSalesInvoiceByPage map:{}", map);
        ResponseMsg msg = new ResponseMsg();
        PageInfo<SalesInvoice> pageInfo = new PageInfo<>();
        pageInfo.setPageNo(map.get("pageNo") == null ? 1 : Integer.parseInt(map.get("pageNo").toString()));
        pageInfo.setPageSize(map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString()));
        Page<Object> page = PageHelper.startPage(pageInfo.getPageNo(), pageInfo.getPageSize(), "order_creation_time desc");
        List<SalesInvoice> salesInvoiceList = salesInvoiceMapper.selectSalesInvoiceByPage(map);
        pageInfo.setList(salesInvoiceList);
        pageInfo.setTotal((int) page.getTotal());
        msg.setData(pageInfo);
        logger.debug("SalesInvoiceServiceImpl selectSalesInvoiceByPage result:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg selectSalesOutByCid(int customerId) {
        logger.info("SalesInvoiceServiceImpl selectSalesOutByCid customerId:{}", customerId);
        ResponseMsg msg = new ResponseMsg();
        List<SalesOut> salesOutList = salesInvoiceMapper.selectSalesOutByCid(customerId);
        if (salesOutList == null || salesOutList.isEmpty()) {
            msg.setCode("301");
            msg.setMsg("查找出库单失败");
            return msg;
        }
        msg.setCode("200");
        msg.setMsg("查找出库单成功");
        msg.setData(salesOutList);
        logger.debug("SalesInvoiceServiceImpl selectSalesOutByCid msg:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg selectSalesOutByCode(String code) {
        logger.info("SalesInvoiceServiceImpl selectSalesOutByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        try {
            List<SalesOutDetail> salesOutDetailList = salesInvoiceMapper.selectSalesOutByCode(code);
            if (salesOutDetailList == null || salesOutDetailList.isEmpty()) {
                msg.setCode("301");
                msg.setMsg("查询销售出库明细失败");
                return msg;
            }
            msg.setCode("200");
            msg.setMsg("查询销售出库明细成功");
            msg.setData(salesOutDetailList);
            return msg;
        } catch (Exception e) {
            logger.error("SalesInvoiceServiceImpl selectSalesOutByCode is error", e);
            msg.setCode("500");
            return msg;
        }
    }

    @Override
    @Transactional
    public ResponseMsg insertSalesInvoice(Map<String, Object> map) {
        logger.info("SalesInvoiceServiceImpl insertSalesInvoice map:{}", map);
        ResponseMsg msg = new ResponseMsg();
        ObjectMapper mapper = new ObjectMapper();

        try {
            // 转换 SalesInvoice 对象
            SalesInvoice salesInvoice = mapper.convertValue(map.get("salesInvoice"), SalesInvoice.class);
            List<?> rawDetails = (List<?>) map.get("details");
            List<SalesInvoiceDetail> details = mapper.convertValue(rawDetails, new TypeReference<List<SalesInvoiceDetail>>() {
            });

            // 设置时间字段
            salesInvoice.setModifyTime(new Date());
            salesInvoice.setOrderCreationTime(new Date());

            salesInvoice.setIsDelete(0);

            // 插入主表
            int result = salesInvoiceMapper.insertSalesInvoice(salesInvoice);
            if (result <= 0) {
                msg.setCode("301");
                msg.setMsg("新增销售发票失败");
                return msg;
            }

            // 插入明细表
            for (SalesInvoiceDetail detail : details) {
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
                detail.setIsDelete(0);
                salesInvoiceMapper.insertSalesInvoiceDetail(detail);
            }

            msg.setCode("200");
            msg.setMsg("新增销售发票成功");
        } catch (Exception e) {
            logger.error("SalesInvoiceServiceImpl insertSalesInvoice error", e);
            msg.setCode("500");
            msg.setMsg("新增销售发票失败: " + e.getMessage());
            throw new RuntimeException("新增销售发票失败", e); // 抛出异常以触发事务回滚
        }

        logger.debug("SalesInvoiceServiceImpl insertSalesInvoice result:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg deleteSalesInvoice(int id) {
        logger.info("SalesInvoiceServiceImpl deleteSalesInvoice id:{}", id);
        ResponseMsg msg = new ResponseMsg();
        int i = salesInvoiceMapper.deleteSalesInvoice(id);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除失败");
        return msg;
    }

    @Override
    public ResponseMsg selectSalesInvoiceByCode(String code) {
        logger.info("SalesInvoiceServiceImpl selectSalesInvoiceByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        SalesInvoice salesInvoice = salesInvoiceMapper.selectSalesInvoiceByCode(code);
        if (salesInvoice != null) {
            msg.setCode("301");
            msg.setData(salesInvoice);
            msg.setMsg("销售发票单据编号重复！");
            logger.debug("SalesInvoiceServiceImpl selectSalesInvoiceByCode msg:{}", msg);
            return msg;
        }
        msg.setCode("200");
        return msg;
    }

    @Override
    public ResponseMsg selectSalesInvoiceDetailByCode(String invoiceCode) {
        logger.info("SalesInvoiceServiceImpl selectSalesInvoiceDetailByCode invoiceCode:{}", invoiceCode);
        ResponseMsg msg = new ResponseMsg();
        List<SalesInvoiceDetail> salesInvoiceDetailList = salesInvoiceMapper.selectSalesInvoiceDetailByCode(invoiceCode);
        if (salesInvoiceDetailList == null || salesInvoiceDetailList.isEmpty()) {
            msg.setCode("301");
            return msg;
        }
        msg.setCode("200");
        msg.setData(salesInvoiceDetailList);
        return msg;
    }

    @Override
    public ResponseMsg deleteSalesInvoiceByCode(String code) {
        logger.info("SalesInvoiceServiceImpl deleteSalesInvoiceByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        int i = salesInvoiceMapper.deleteSalesInvoiceByCode(code);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除销售订单主表数据成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除销售订单主表数据失败");
        return msg;
    }

    @Override
    public ResponseMsg deleteSalesDetailsByCode(String code) {
        logger.info("SalesInvoiceServiceImpl deleteSalesDetailsByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        int i = salesInvoiceMapper.deleteSalesDetailsByCode(code);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除销售订单明细表数据成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除销售订单明细表数据失败");
        return msg;
    }

    @Override
    public ResponseMsg getOutStoreList(Map<String, Object> map) {
        logger.info("InStoreServiceImpl getOutStoreList map:" + map);
        ResponseMsg msg = new ResponseMsg();
        PageInfo<OutStore> pageInfo = new PageInfo<>();
        if (map.containsKey("pageNo")) {
            pageInfo.setPageNo(Integer.valueOf(map.get("pageNo").toString()));
        }
        if (map.containsKey("pageSize")) {
            pageInfo.setPageSize(Integer.valueOf(map.get("pageSize").toString()));
        }
        Page<Object> page = PageHelper.startPage(pageInfo.getPageNo(), pageInfo.getPageSize());
        List<OutStore> outStoreList = salesInvoiceMapper.getOutStoreList(map);
        logger.debug("InStoreServiceImpl getInStoreList outStoreList:" + outStoreList);
        pageInfo.setList(outStoreList);
        pageInfo.setPages(page.getPages());
        pageInfo.setTotal((int) page.getTotal());
        msg.setCode("200");
        msg.setData(pageInfo);
        logger.debug("InStoreServiceImpl getInStoreList msg:" + msg);
        return msg;
    }


}
